package com.fusheng.demo.accessibilityservice

import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.provider.Settings
import androidx.core.content.ContextCompat.startActivity


/**
 *  无障碍模式工具
 */
class AccessibilityUtils private constructor() {

    companion object {

        @JvmStatic
        val instant by lazy {
            AccessibilityUtils()
        }

    }


    /**
     * 判读无障碍服务是否打开
     */
    fun isServiceON(context: Context, className: String?): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningServices = activityManager.getRunningServices(100)
        if (runningServices.size < 0) {
            return false
        }
        for (i in runningServices.indices) {
            val service = runningServices[i].service
            if (service.className.contains(className!!)) {
                return true
            }
        }
        return false
    }


    /**
     * 打开无障碍设置入口
     */
    fun openService(context: Context, clazz: Class<*>) {
        if (!isServiceON(context, clazz.name)) {
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(context, intent, null)
        } else {
            context.startService(Intent(context, clazz))
        }
    }

}